package com.hqyj.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.hqyj.excepiton.JwtException;
import com.hqyj.utile.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目:exam-springboot-230701
 * 描述:
 * 时间:2023/10/7 15:24
 * 作者:admin
 * 版本:1.0
 **/
public class JwtAnInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取拦截方法上的自定义注解JwtToken
        HandlerMethod handlerMethod =(HandlerMethod)handler;
        JwtToken jwtToken =handlerMethod.getMethod().getAnnotation(JwtToken.class);
        if(jwtToken!=null){
            //获取token
            String token = request.getHeader("Authorization");
            //1 判断是否为空
            if(StringUtils.isEmpty(token)){
                throw new JwtException(300,"请重新登录","token为空");
            }
            //2 获取token的用户id,判断token是否是伪造的
            String id = JwtUtil.getAudience(token);
            if(id==null){
                throw new JwtException(300,"请重新登录","token错误");
            }
            //3 判断token是否过期
            //获取盐值
            String salt = JwtUtil.getClaimByName(token,"jwtSalt").asString();
            DecodedJWT jwt = JwtUtil.verifyToken(token,salt);
            if(jwt==null){
                throw new JwtException(300,"请重新登录","token过期");
            }
        }

        return true;
    }
}
